import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-03-17
 * Time: 22:50
 */
public class Main {
    public int totalFruit(int[] fruits) {
        Map<Integer,Integer> hash  = new HashMap<Integer, Integer>();
        int ret = 0;
        for (int left = 0,right = 0; right < fruits.length; right++) {
            int in = fruits[right];
            hash.put(in,hash.getOrDefault(in,0)+1);
            while (hash.size()>2){
                int out = fruits[left];
                hash.put(out,hash.get(out)-1);
                if (hash.get(out) == 0){
                    hash.remove(out);
                }
                left++;
            }
            //更新结果
            ret = Math.max(ret,right-left+1);
        }
        return ret;
    }
    //数组
    public int totalFruit1(int[] fruits) {
        int n = fruits.length;
        int[] hash = new int[n+1];
        int ret = 0;
        for (int left = 0,right = 0,kinds = 0; right < n; right++) {
            int in = fruits[right];
            if (hash[in] == 0){
                kinds++;
            }
            hash[in]++;
            while (kinds > 2){
                int out = fruits[left];
                hash[out]--;
                if (hash[out] == 0){
                    kinds--;
                }
                left++;
            }
            //更新结果
            ret = Math.max(ret,right-left+1);
        }
        return ret;
    }
}
